function varargout = TrajViewer(varargin)
% TRAJVIEWER M-file for TrajViewer.fig
%      TRAJVIEWER, by itself, creates a new TRAJVIEWER or raises the existing
%      singleton*.
%
%      H = TRAJVIEWER returns the handle to a new TRAJVIEWER or the handle to
%      the existing singleton*.
%
%      TRAJVIEWER('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in TRAJVIEWER.M with the given input arguments.
%
%      TRAJVIEWER('Property','Value',...) creates a new TRAJVIEWER or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before TrajViewer_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to TrajViewer_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help TrajViewer

% Last Modified by GUIDE v2.5 05-Apr-2010 10:44:19

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @TrajViewer_OpeningFcn, ...
                   'gui_OutputFcn',  @TrajViewer_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before TrajViewer is made visible.
function TrajViewer_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to TrajViewer (see VARARGIN)

% Choose default command line output for TrajViewer
%
%
%outdir = 'C:\Users\Michael Ferry\experiments\MF220\analysis_data\xy2\matPIV\';

%
handles.output = hObject;
handles.Objects=varargin{1}{1};
handles.Traj=varargin{1}{2};
handles.TrajInFrames=varargin{1}{3};
handles.velocityfield=varargin{1}{4};
handles.parameters = varargin{1}{5};

set(handles.edit3,'String',num2str(handles.parameters.alpha));
set(handles.edit4,'String',num2str(handles.parameters.beta));
set(handles.edit5,'String',num2str(handles.parameters.epsilon));
set(handles.edit6,'String',num2str(handles.parameters.gamma));

handles.viewer1Handles.plotFigure=[];
handles.viewer2Handles.plotFigure=[];

guidata(hObject, handles);

% UIWAIT makes TrajViewer wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = TrajViewer_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

 %handles.plotFigure=figure('NextPlot','replace');
%handles.scroll_panel=[];
%handles=write_traj_image(handles,handles.output_write_seg,handles.segfilenames,handles.Objects,handles.Traj,1,'number');
%fileNames=handles.segfilenames(1:10);
%handles.figList=LoadTrajStack(handles.text1,handles.output_write_seg,fileNames,handles.Traj);
displayComparisonImages(handles)
guidata(hObject, handles);



% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%handles.plotFigure=figure('NextPlot','replace');
%handles.scroll_panel=[];
%handles=write_traj_image(handles,handles.rgb,handles.Objects,handles.Traj,1,'number');
%write_traj_image(handles.figList,1);
%WriteTrajStack('',handles.output_write_seg,handles.segfilenames,handles.Traj)
slice(1) = str2double(get(handles.edit1,'String'));
slice(2) = str2double(get(handles.edit2,'String'));
%showTranslatedObjectsByVelocityField(handles.velocityfield,slice)
showTranslatedObjectsByVelocityField(handles.parameters.maskfilenames,handles.velocityfield,slice)
guidata(hObject, handles);

% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
slice(1) = str2double(get(handles.edit1,'String'));
slice(2) = str2double(get(handles.edit2,'String'));
%PlotVelocityFieldPhase(handles.velocityfield,handles.,handles.phasefilenames,handles.Traj,handles.Objects,slice)
PlotVelocityFieldPhase(handles.velocityfield,handles.parameters,...
    handles.Traj,handles.TrajInFrames,handles.Objects,slice(1))

% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listbox1

displayComparisonImages(handles)



function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double
slice = str2double(get(hObject,'string'));
updateTrajList(slice,handles.TrajInFrames,handles.listbox1)


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double
%slice = str2double(get(hObject,'string'));
% [handles.viewer2Handles]=write_traj_image(handles.viewer2Handles,handles.output_write_seg,...
%     handles.segfilenames,handles.Objects,handles.Traj,slice,'number');


% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function updateTrajList(slice,TrajInFrames,listboxHandle)
cellList=num2cell(TrajInFrames{slice});
set(listboxHandle,'String',cellList);

function displayComparisonImages(handles)
parameters=handles.parameters;
ON=parameters.ON;
TN=parameters.TN;
CP=parameters.CP;

contents = cellstr(get(handles.listbox1,'String'));
selection = str2double(contents{get(handles.listbox1,'Value')});
%selection
frameToConsider = str2double(get(handles.edit1,'String'));
slice(2) = str2double(get(handles.edit2,'String'));

prevFrame=frameToConsider-1;

parameters.alpha = str2double(get(handles.edit3,'String'));
parameters.beta = str2double(get(handles.edit4,'string'));
parameters.epsilon = str2double(get(handles.edit5,'string'));
parameters.gamma = str2double(get(handles.edit6,'string'));


options.table=handles.uitable1;

%remove the sections of the Trajectory cell which correspond to time points after the frame of interest
earlierTraj=RollbackTrajToEarlierState(handles.Traj,prevFrame,parameters);
%Process the data
[TrajFromBin,TrajBin]=CreateTrajBinFromActiveTraj(prevFrame,handles.TrajInFrames{prevFrame},...
    handles.Objects,earlierTraj,handles.velocityfield,parameters);
[~,~,ObjCalcProps]=ProcessSingleFrameForTrajectories(frameToConsider,TrajFromBin,TrajBin,...
    handles.TrajInFrames{prevFrame},handles.Objects{frameToConsider},parameters);
%Create a score matrix from the ObjCalcProps which includes the
%Object number
scoreMatrix = ConvertObjCalcPropsToScoreMatrix(ObjCalcProps);
parameters.CP.object=4;

LogicalObjectsToProcess=scoreMatrix(:,parameters.CP.trajNumber)==selection;
scoredObjectsToProcess=scoreMatrix(LogicalObjectsToProcess,:);
[~,sortedInd]=sort(scoredObjectsToProcess(:,parameters.CP.score),'ascend');
sortedScoredObjectsToProcess=scoredObjectsToProcess(sortedInd,:);

[numOfScoredObjects, NumTN]=size(sortedScoredObjectsToProcess);

%find the all frames the trajectory appeared in before the frame of
%interest up to and including this frame
FramesBeforeSelectionForTraj=handles.Traj{selection}(:,TN.frame)<frameToConsider;
%Of these frames find the last frame up to and including the current frame
%that the trajectory appeared in.  Note this is necessary because a
%trajectory may not be in this frame but still may be active, if the
%numOfPreviousFramesToConsider parameter is greater than 1
ClosestFrameForTrajToSelection= abs(handles.Traj{selection}(FramesBeforeSelectionForTraj,TN.frame)-frameToConsider)...
    ==(min(abs(handles.Traj{selection}(FramesBeforeSelectionForTraj,TN.frame)-frameToConsider)));
%TrajSlice=abs(handles.Traj{selection}(:,TN.frame)-slice(1))==(min(abs(handles.Traj{selection}(:,TN.frame)-slice(1))));
TrajObjNum=handles.Traj{selection}(ClosestFrameForTrajToSelection,TN.object);
lastFrameTrajAppeared=handles.Traj{selection}(ClosestFrameForTrajToSelection,TN.frame);

BaseTrajObject=handles.Objects{lastFrameTrajAppeared}(TrajObjNum,:);
PredictedTrajObject = GetPredictedObject(BaseTrajObject,handles.velocityfield,frameToConsider,lastFrameTrajAppeared,parameters);
PredictedTrajObject(ON.Number)=NaN;


%tableCell{2,1}='Traj Number';
tableCell{1,2}='Trajectory';
tableCell{1,3}=selection;
tableCell{1,4}='Objects';
tableCell{2,2}='Base';
tableCell{2,3}='Predicted';
tableCell{3,1}='Last frame traj appeared';
tableCell{3,2}=lastFrameTrajAppeared;
tableCell{3,4}='score';

ONnames=fieldnames(parameters.ON);
ONnames{parameters.ON.Number}='Object';
for i=1:length(ONnames)
    tableCell{3+i,1}=ONnames{i};
    tableCell{3+i,2}=BaseTrajObject(i);
    tableCell{3+i,3}=PredictedTrajObject(i);
end
for j=1:numOfScoredObjects
    ObjectNum=sortedScoredObjectsToProcess(j,parameters.CP.object);
    ObjectForOutput=handles.Objects{frameToConsider}(ObjectNum,:);
    tableCell{3,4+j}=sortedScoredObjectsToProcess(j,parameters.CP.score);
    for k=1:length(ONnames)
        tableCell{3+k,4+j}=ObjectForOutput(k);
    end
end

set(options.table,'Data',tableCell);
latextable(tableCell(:,1:8))
[handles.viewer1Handles]=WriteTrajIndivDbl(handles.viewer1Handles,sortedScoredObjectsToProcess,handles.Objects{frameToConsider},...
    lastFrameTrajAppeared,TrajObjNum,frameToConsider,PredictedTrajObject,BaseTrajObject,parameters);


% %[handles.viewer1Handles]=WriteTrajIndiv(handles.viewer1Handles,selection,handles.output_write_seg,...
% %    handles.segfilenames,handles.Objects,handles.Traj,slice,'number');
% ObjectsInNextFrame=handles.Objects{slice(1)+1};
% 
% %Intialize objects in current frame to contain the trajectory
% %processing data fields, especially important for parfor loops
% 
% [numOfObjectsInFrame,ONprops]=size(ObjectsInNextFrame);
% ObjCalcProps=cell(numOfObjectsInFrame,1);
% 
% [TrajFromTrajBin,TrajBin]=CreateTrajBinFromActiveTraj(slice(1),handles.TrajInFrames{slice(1)},...
%     handles.Objects,handles.Traj,handles.velocityfield,handles.parameters);
% 
% ObjBin=cell(parameters.binnedDimensions(1),parameters.binnedDimensions(2));
% for i=1:numOfObjectsInFrame
%     BaseObject=ObjectsInNextFrame(i,:);
% 
%     %Place the trajectory object into the TrajBin based on its updated
%     %centroid location
%     [BinX BinY]=getBinCoords([BaseObject(ON.CentroidX) BaseObject(ON.CentroidY)],handles.parameters.binSize); 
%     ObjBin{BinX,BinY}(end+1,:)=BaseObject;
% end
% %find the all frames the trajectory appeared in before the frame of
% %interest up to and including this frame
% FramesBeforeSelectionForTraj=handles.Traj{selection}(:,TN.frame)<=slice(1);
% %Of these frames find the last frame up to and including the current frame
% %that the trajectory appeared in.  Note this is necessary because a
% %trajectory may not be in this frame but still may be active, if the
% %numOfPreviousFramesToConsider parameter is greater than 1
% ClosestFrameForTrajToSelection= abs(handles.Traj{selection}(FramesBeforeSelectionForTraj,TN.frame)-slice(1))...
%     ==(min(abs(handles.Traj{selection}(FramesBeforeSelectionForTraj,TN.frame)-slice(1))));
% %TrajSlice=abs(handles.Traj{selection}(:,TN.frame)-slice(1))==(min(abs(handles.Traj{selection}(:,TN.frame)-slice(1))));
% TrajObjNum=handles.Traj{selection}(ClosestFrameForTrajToSelection,TN.object);
% lastFrameTrajAppeared=handles.Traj{selection}(ClosestFrameForTrajToSelection,TN.frame);
% 
% BaseTrajObject=handles.Objects{lastFrameObjectAppeared}(TrajObjNum,:);
% PredictedTrajObject = GetPredictedObject(BaseTrajObject,handles.velocityfield,slice(1),lastFrameObjectAppeared,parameters);
% 
% ObjCalcProps=CalculateObjectProperties(PredictedTrajObject,ObjBin,parameters);
% 
% ObjectsInNextFrameWithScores=[ ObjectsInNextFrame(ObjCalcProps(:,CP.trajNumber),:) ObjCalcProps(:,CP.score)];
% [vals,ix]=sort(ObjectsInNextFrameWithScores(:,end),'ascend');
% SortedObjectsInNextFrameWithScores=ObjectsInNextFrameWithScores(ix,:);
%end
%'test'
%[handles.viewer1Handles]=WriteTrajIndivDbl(handles,selection,...
 %   handles.ObjectsContainedInFrames,handles.Traj,TrajBin,ObjCalcProps,slice,options,params);

%[handles.viewer1Handles]=WriteTrajIndivDbl(handles.viewer1Handles,selection,...
   % handles.parameters.maskfilenames,handles.Objects,handles.Traj,handles.TrajBin,slice,options);


function edit3_Callback(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit3 as text
%        str2double(get(hObject,'String')) returns contents of edit3 as a double


% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit4_Callback(hObject, eventdata, handles)
% hObject    handle to edit4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit4 as text
%        str2double(get(hObject,'String')) returns contents of edit4 as a double


% --- Executes during object creation, after setting all properties.
function edit4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit5_Callback(hObject, eventdata, handles)
% hObject    handle to edit5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit5 as text
%        str2double(get(hObject,'String')) returns contents of edit5 as a double


% --- Executes during object creation, after setting all properties.
function edit5_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit6_Callback(hObject, eventdata, handles)
% hObject    handle to edit6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit6 as text
%        str2double(get(hObject,'String')) returns contents of edit6 as a double


% --- Executes during object creation, after setting all properties.
function edit6_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
% --- Executes on slider movement.
function slider1_Callback(hObject, eventdata, handles)
% hObject    handle to slider1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
%slider_position=round(get(hObject,'Value'));
%slider_position
%get(hObject,'Max')
%write_object_image(handles.axes1,handles.output_write_seg,handles.segfilenames,handles.Objects,slider_position,'number');
%handles
%set(handles.text1,'String',num2str(slider_position));
%handles=write_traj_image(handles,handles.rgb,handles.Objects,handles.Traj,slider_position,'number');
%write_traj_image(handles.figList,slider_position);
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function slider1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to slider1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
